use axum::{extract::{MatchedPath, State}, http::StatusCode, response::Html, routing::get, Extension, Router};
use tracing::debug;

use super::{service_tree::ServiceParts, UserSessionState, AppState};


pub fn service_router<'t>(state: AppState, service_parts: ServiceParts<'t>) -> Router<AppState> {
    let root = service_parts.root_as_str();

    let templates = service_parts.templates.into_iter();
        //.map(|s| s.strip_prefix(root).expect("no root prefix ina template name"));

    let r = Router::new()
        .route("/", get(get_flatpages));

    let r = templates.fold(r, |r, path| r.route(
        &("/".to_string() + path), 
        get(get_flatpages)
    ));

    r.with_state(state.with_root(root.to_owned()))

}

async fn get_flatpages(
    State(AppState { root, render, ..}): State<AppState>,
    Extension(uss): Extension<UserSessionState>,
    matched_path: MatchedPath,
) -> (StatusCode, Html<String>) {
    debug!(message="get_flatpages", root=root.as_ref(), matched_path=matched_path.as_str());

    let path = matched_path.as_str().strip_prefix('/').unwrap_or(matched_path.as_str());
    let path = if path == "" { "index.html" } else { path };

    let template_name = format!("{root}{path}");

    //debug!(template_name=template_name);
    render.render(&template_name, &uss.context)
}